package com.chenyu.util;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.*;

/**
 * JAVA对象持久化
 *
 * @author jianggujin
 *
 */
public class JavaSerializable {
    /**
     * 持久化为XML对象
     *
     * @param obj  对象
     * @param storeName1  持久化路径
     */
    public void storeXML(Object obj, String storeName1) throws FileNotFoundException {
        XMLEncoder encoder = null;
        try {
            File xmlFile = new File(storeName1);
            encoder = new XMLEncoder(new FileOutputStream(xmlFile));
            encoder.writeObject(obj);
        }finally {
            if(null != encoder){
                encoder.flush();
                encoder.close();
            }
        }

    }

    /**
     * 从XML中加载对象
     *
     * @param path
     * @return
     */
    public Object loadXML(String path)  throws FileNotFoundException {
        File file = new File(path);
        XMLDecoder decoder = null;
        Object obj;
        try{
            decoder = new XMLDecoder(new FileInputStream(file));
            obj = decoder.readObject();
        }finally {
            if(null != decoder){
                decoder.close();
            }
        }
        return obj;
    }

    /**
     * 持久化对象
     *
     * @param obj
     * @param fiilePath
     * @throws IOException
     */
    public void store(Object obj, String fiilePath) throws IOException {
        File file = new File(fiilePath);
        ObjectOutputStream outputStream = null;
        try{
            outputStream = new ObjectOutputStream( new FileOutputStream(file));
            outputStream.writeObject(obj);
        }finally {
            if(null != outputStream){
                outputStream.flush();
                outputStream.close();
            }
        }
    }

    /**
     * 加载对象
     *
     * @param path
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public Object load(String  path) throws IOException,ClassNotFoundException {
        File file = new File(path);
        Object obj;
        ObjectInputStream inputStream = null;
        try {
            inputStream = new ObjectInputStream(new FileInputStream(file));
            obj = inputStream.readObject();
        }finally {
            if(null != inputStream){
                inputStream.close();
            }
        }
        return obj;
    }
}
